<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"
              ><span class="el-custom-title">工序组管理</span></el-col
            >
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="handleUpdate()"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="ui_delete(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-tree
              ref="tree2"
              :data="data2"
              :props="defaultProps"
              class="filter-tree"
              default-expand-all
              @node-click="clickNode"
              v-if="this.openPanel"
            />
          </el-row>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"
              ><span class="el-custom-title">工序管理</span></el-col
            >
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreateSon"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleUpdateSon()"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="ui_deleteSon(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              ref="dataTable"
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChangeSon"
            >
              >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="工序编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.procedureNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="工序名称"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.procedureName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="单价"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.unitPrice }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="产品类型"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.productTypeName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.ordered }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="备注"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.comment }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="标准工时"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.standardWorkhours }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="费率"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.fee }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <pagination
              v-show="total2 > 0"
              :total="total2"
              :page.sync="listQuery2.page"
              :limit.sync="listQuery2.limit"
              :page-sizes="listQuery2.pageSizes"
              @pagination="fetchDataSon"
            />
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-tabs type="border-card">
        <el-tab-pane label="标准指导书">
          <mesproceduresoplist
            :procedure="
              this.lstSelectedSon != null && this.lstSelectedSon.length > 0
                ? this.lstSelectedSon[0]
                : null
            "
          ></mesproceduresoplist>
        </el-tab-pane>
        <el-tab-pane label="工艺">
          <mesproceduresetchild
            :mesprocedureid="
              this.lstSelectedSon != null &&
              this.lstSelectedSon.length > 0 &&
              this.lstSelectedSon[0].id != null
                ? this.lstSelectedSon[0].id
                : 0
            "
          ></mesproceduresetchild
        ></el-tab-pane>
        <el-tab-pane label="工序动作组">配置管理</el-tab-pane>
        <el-tab-pane label="工序动作库">角色管理</el-tab-pane>
        <el-tab-pane label="工序变量">定时任务补偿</el-tab-pane>
        <el-tab-pane label="工序要求">定时任务补偿</el-tab-pane>
        <el-tab-pane label="观测工时">定时任务补偿</el-tab-pane>
      </el-tabs>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工段" prop="temp.workSectionId">
          <el-select
            v-model="temp.workSectionId"
            class="filter-item"
            placeholder="请选择工段"
            @change="handleMainTypeChange"
          >
            <el-option
              v-for="item in this.data2.length > 0 &&
              this.data2[0].children != null &&
              this.data2[0].children.length > 0
                ? data2[0].children
                : []"
              :key="item.id"
              :label="item.procedureSetName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级工序组" prop="temp.parentId">
          <el-select
            v-model="temp.parentId"
            class="filter-item"
            placeholder="请选择工序组"
            @change="handleMainTypeChange"
          >
            <el-option
              v-for="item in this.ddWorkSets"
              :key="item.id"
              :label="item.procedureSetName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序组编号" prop="procedureSetNo">
          <el-input v-model="temp.procedureSetNo" />
        </el-form-item>
        <el-form-item label="工序组名称" prop="procedureSetName">
          <el-input v-model="temp.procedureSetName" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="textMap[dialogStatusSon]"
      :visible.sync="dialogFormVisibleSon"
    >
      <el-form
        ref="dataFormson"
        :rules="rulesson"
        :model="tempson"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工序编号" prop="procedureNo">
          <el-input v-model="tempson.procedureNo" />
        </el-form-item>
        <el-form-item label="工序名称" prop="procedureName">
          <el-input v-model="tempson.procedureName" />
        </el-form-item>
        <el-form-item label="单价" prop="Definition">
          <el-input v-model="tempson.unitPrice" />
        </el-form-item>
        <el-form-item label="产品类型" prop="productTypeId">
          <el-select
            v-model="tempson.productTypeId"
            class="filter-item"
            placeholder="请选择产品类型"
          >
            <el-option
              v-for="item in this.ddProductTypes"
              :key="item.id"
              :label="item.productTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="序号" prop="enable">
          <el-select
            v-model="tempson.enable"
            class="filter-item"
            placeholder="请输入序号"
          >
            <el-option
              v-for="item in [
                { id: false, enable: '不启用' },
                { id: true, enable: '启用' }
              ]"
              :key="item.id"
              :label="item.enable"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="tempson.comment" />
        </el-form-item>

        <el-form-item label="标准工时" prop="standardWorkhours">
          <el-input v-model="tempson.standardWorkhours" />
        </el-form-item>
        <el-form-item label="费率" prop="fee">
          <el-input v-model="tempson.fee" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleSon = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatusSon === 'create' ? ui_createSon() : ui_updateSon()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";

import {
  getAll,
  getList,
  create,
  update,
  deleteBatch
} from "@/api/procedure/mesProcedureSet";

import {
  getAllSon,
  listSon,
  createSon,
  updateSon,
  deleteBatchSon,
  getProcedureResources
} from "@/api/procedure/mesProcedure";

import { getAll as getAllProductTypes } from "@/api/mesProductType";
import mesproceduresoplist from "@/views/procedure/mesproceduresoplist";
import mesproceduresetchild from "@/views/procedure/mesproceduresetchild";
import { deletePicture } from "@/api/mesTechnologySOP";
import { createRelation } from "@/api/procedure/mesProcedureTechnology";
import { validFloat } from "@/utils/validate";

export default {
  components: { Pagination, mesproceduresoplist, mesproceduresetchild },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    const validateFloat = (rule, value, callback) => {
      if (!validFloat(value)) {
        callback(new Error("请输入不小于0的数值"));
      } else {
        callback();
      }
    };
     const validateProductTypeId = (rule, value, callback) => {
      let val = parseInt(value)
      if (val == null || val == 0) {
        callback(new Error("请选择产品类型!"));
      } else {
        callback();
      }
    };
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "procedureSetName"
      },
      list: null,
      list2: null,
      listLoading: true,
      total2: 0,
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentMesProcedureSetId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        procedureSetNo: [
          {
            required: true,
            message: "工序组编号不能为空！",
            trigger: "change"
          }
        ],
        procedureSetName: [
          {
            required: true,
            message: "工序组名称不能为空！",
            trigger: "change"
          }
        ],
        workSectionId: [
          {
            required: true,
            message: "所属工段不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: undefined,
        procedureSetNo: "",
        procedureSetName: "",
        workSectionId: 0,
        comment: ""
      },
      //表格變量
      lstSelected: [],
      currentMesProcedureSet: null,
      dialogFormVisibleSon: false,
      dialogStatusSon: "",
      rulesson: {
        procedureNo: [
          {
            required: true,
            message: "工序编号不能为空！",
            trigger: "change"
          }
        ],
        procedureName: [
          {
            required: true,
            message: "工序名称不能为空！",
            trigger: "change"
          }
        ],
        unitPrice: [
          {
            required: true,
            message: "定义不能为空！",
            trigger: "change"
          }
        ],
        productTypeId: [
          {
            required: true,
            trigger: "change",
            validator:validateProductTypeId
          }
        ],
        ordered: [
          {
            required: true,
            message: "是否启动不能为空！",
            trigger: "change"
          }
        ],
        standardWorkhours: [
          {
            type: "float",
            validator: validateFloat,
            required: true,
            trigger: "blur"
          }
        ],
        fee: [
          {
            type: "float",
            validator: validateFloat,
            required: true,
            trigger: "blur"
          }
        ]
      },
      tempson: {
        id: 0,
        procedureNo: "",
        procedureName: "",
        Definition: "",
        productTypeId: 0,
        procedureSetId:0,
        enable: false,
        comment: "",
        standardWorkhours: 0.0,
        fee: 0.0
      },
      //表格變量
      lstSelectedSon: [],
      lstWorkSetctions: [],
      lstParentIds: [],
      openPanel: true,
      ddWorkSets: [],
      ddProductTypes: []
    };
  },
  filters: {
    resolveEnableValue(p) {
      return p ? "是" : "否";
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    },
    list2: function() {
      if (this.list2 != null && this.list2.length > 0) {
        this.$nextTick(function() {
          this.$refs.dataTable.setCurrentRow(this.list2[0]);
          this.lstSelectedSon.length = 0;
          this.lstSelectedSon.push(this.list2[0]);
        });
      }
    }
  },
  created() {
    this.fetchData();
    this.fetchDataSon(0);
    this.getAllProductTypes();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      this.data2 = [];
      this.listLoading = true;
      let params = {
        name: ""
      };
      getAll(params).then(response => {
        this.data2.push(response.data);
        this.listLoading = false;
      });
    },
    clickNode(data, node, obj) {
      this.lstSelected = [];
      if (data.parentId == -1) return;
      this.lstSelected.push(data);
      this.currentMesProcedureSetId = data.id
      this.temp = Object.assign({}, data);
      let params = {
        procedureSetId: data.id,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };
      getProcedureResources(params).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          if (this.temp.parentId == null) {
            this.temp.parentId = 0;
          }
          create(this.temp).then(() => {
            this.updateTree(false);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.temp.parentId == null) {
            this.temp.parentId = 0;
          }
          update(this.temp).then(() => {
            //刷新UI
            this.updateTree(false);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的工序组");
        return;
      }
      let ids = [];
      this.lstSelected.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatch(ids).then(() => {
        this.updateTree(true);
        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        procedureSetNo: "",
        procedureSetName: "",
        workSectionId: 0,
        comment: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条工序组");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.getSelParentIdOptions();
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleSelectionChangeSon(val) {
      if (val == null || val.length == 0) return;
      this.lstSelectedSon = val;
      const type = this.ddProductTypes.find(
        v => v.productTypeName == val[0].ddProductTypeName
      );
      if (type != null) {
        this.tempson.productTypeId = type.id;
      }
    },
    fetchDataSon() {
      let params = {
        TherbligsTypeId: this.currentMesProcedureSet,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };
      return getProcedureResources(params).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.lstSelectedSon.length = 0;
      this.lstSelectedSon.push(row);
      this.currentMesProcedure = row;
    },
    resetTempSon() {
      this.tempson = {
        id: 0,
        procedureNo: "",
        procedureName: "",
        Definition: "",
        productTypeId: 0,
        procedureSetId:0,
        enable: false,
        comment: "",
        standardWorkhours: 0.0,
        fee: 0.0
      };
    },
    handleCreateSon() {
      if (
        this.lstSelected == null ||
        this.lstSelected.length !== 1 ||
        parseInt(this.lstSelected[0].parentId) < 0
      ) {
        this.$message.error("请先选择一条标准工序组");
        return;
      }
      this.resetTempSon();
      this.dialogStatusSon = "create";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    handleUpdateSon() {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length !== 1) {
        this.$message.error("请先选择一条标准工序");
        return;
      }
      this.tempson = Object.assign({}, this.lstSelectedSon[0]); // copy obj
      let cur = this.ddProductTypes.find(
        v => v.productTypeName == this.lstSelectedSon[0].productTypeName
      );
      this.tempson.productTypeId = cur != null ? cur.id : 0;
      this.tempson = { ...this.tempson };
      this.dialogStatusSon = "update";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    ui_createSon() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          this.tempson.id = 0; //自增
          this.tempson.procedureSetId = this.currentMesProcedureSetId
          createSon(this.tempson).then(() => {
            //动态添加name属性
            this.tempson.productTypeName = this.ddProductTypes.find(
              v => v.id == this.tempson.productTypeId
            ).productTypeName;
            this.list2.unshift(this.tempson);
            this.dialogFormVisibleSon = false;
              this.$notify({
                title: "Success",
                message: "添加成功！",
                type: "success",
                duration: 2000
              });
          });
        }
      });
    },
    ui_updateSon() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          updateSon(this.tempson).then(() => {
            const index = this.list2.findIndex(v => v.id === this.tempson.id);
            //动态添加name属性
            this.tempson.productTypeName = this.ddProductTypes.find(
              v => v.id == this.tempson.productTypeId
            ).productTypeName;
            this.list2.splice(index, 1, this.tempson);
            //delete  this.tempson.productTypeName
            this.dialogFormVisibleSon = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_deleteSon(row, index) {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length === 0) {
        this.$message.error("请先选择要删除的工序");
        return;
      }
      let ids = [];
      this.lstSelectedSon.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatchSon(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list2.findIndex(v => v.id === elm);
          this.list2.splice(index, 1);
        });
        this.dialogFormVisibleSon = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    handleMainTypeChange(val) {
      this.getSelParentIdOptions();
    },
    getSelParentIdOptions() {
      this.ddWorkSets = [];
      this.ddWorkSets.push({ id: 0, procedureSetName: "请选择" });
      //如果没有选中的同工序组则列出所有的一级工序组
      if (this.temp.workSectionId > 0) {
        const workset =
          this.data2 != null &&
          this.data2[0].children.find(v => v.id === this.temp.workSectionId);
        if (workset != null && workset.children != null) {
          this.ddWorkSets.push(...workset.children);
        }
      } else {
        if (
          this.data2 != null &&
          this.data2[0].children != null &&
          this.data2[0].children.length > 0
        ) {
          this.data2[0].children.forEach(v => {
            if (v.children != null && v.children.length > 0) {
              this.ddWorkSets.push(...v.children);
            }
          });
        }
      }
    },
    updateTree(isDel) {
      if (isDel && this.temp.id == 0) {
        this.$message.error("数据处于草稿状态，请先刷新页面再删除！");
        return;
      }
      //先找到工段(更新)
      if (
        this.data2 != null &&
        this.data2[0].children != null &&
        this.data2[0].children.length > 0
      ) {
        let worksection = this.data2[0].children.find(
          v => v.id == this.temp.workSectionId
        );
        if (worksection != null) {
          if (this.temp.parentId == 0) {
            //从第三级找
            if (this.temp.id > 0) {
              //更新
              let idx = worksection.children.findIndex(
                v => v.id == this.temp.id
              );
              if (idx >= 0) {
                if (!isDel) {
                  worksection.children.splice(idx, 1, this.temp);
                } //删除
                else {
                  worksection.children.splice(idx, 1);
                }
              }
            } //增加
            else {
              worksection.children.push(this.temp);
            }
          } //从第四级找
          else {
            let parentIdx = worksection.children.findIndex(
              v => v.id == this.temp.parentId
            );
            if (parentIdx >= 0) {
              let parent = worksection.children[parentIdx];
              if (this.temp.id > 0) {
                //更新
                let idx = parent.children.findIndex(v => v.id == this.temp.id);
                if (!isDel) {
                  parent.children.splice(idx, 1, this.temp);
                } //删除
                else {
                  parent.children.splice(idx, 1);
                }
              } //增加
              else {
                parent.children.push(this.temp);
              }
            }
          }
        }
      }
    },
    getAllProductTypes() {
      getAllProductTypes().then(response => {
        this.ddProductTypes.push({ id: 0, productTypeName: "请选择" });
        this.ddProductTypes.push(...response.data);
      });
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
